package com.example.chamberlainserver.controller;

import com.example.chamberlainserver.Entry.ScheduleAssignment;
import com.example.chamberlainserver.Service.ScheduleAssignmentService;
import com.example.chamberlainserver.Vo.Response.ApiResponse;
import com.example.chamberlainserver.dto.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 排班分配控制器
 */
@RestController
@RequestMapping("/schedule/assignments")
public class ScheduleAssignmentController {

    @Autowired
    private ScheduleAssignmentService scheduleAssignmentService;

    /**
     * 添加排班分配
     */
    @PostMapping("/add")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> addScheduleAssignment(@RequestBody ScheduleAssignment assignment) {
        try {
            // 设置创建人
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            // 这里需要根据username获取userId，暂时设置为1
            assignment.setCreatedBy(1);
            
            boolean success = scheduleAssignmentService.addScheduleAssignment(assignment);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("添加排班分配成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("添加排班分配失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("添加排班分配失败: " + e.getMessage()));
        }
    }

    /**
     * 批量添加排班分配
     */
    @PostMapping("/batch/add")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> batchAddScheduleAssignments(@RequestBody List<ScheduleAssignment> assignments) {
        try {
            // 设置创建人
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            // 这里需要根据username获取userId，暂时设置为1
            for (ScheduleAssignment assignment : assignments) {
                assignment.setCreatedBy(1);
            }
            
            boolean success = scheduleAssignmentService.batchAddScheduleAssignment(assignments);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("批量添加排班分配成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("批量添加排班分配失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("批量添加排班分配失败: " + e.getMessage()));
        }
    }

    /**
     * 根据ID获取排班分配
     */
    @GetMapping("/get/{id}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<ScheduleAssignment>> getScheduleAssignmentById(@PathVariable String id) {
        try {
            ScheduleAssignment assignment = scheduleAssignmentService.getScheduleAssignmentById(id);
            
            if (assignment != null) {
                return ResponseEntity.ok(ApiResponse.success("获取排班分配成功", assignment));
            } else {
                return ResponseEntity.ok(ApiResponse.error(404, "排班分配不存在"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取排班分配失败: " + e.getMessage()));
        }
    }

    /**
     * 根据用户ID获取排班分配列表
     */
    @GetMapping("/user/{userId}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<ScheduleAssignment>>> getScheduleAssignmentsByUserId(@PathVariable Integer userId) {
        try {
            List<ScheduleAssignment> assignments = scheduleAssignmentService.getScheduleAssignmentsByUserId(userId);
            return ResponseEntity.ok(ApiResponse.success("获取用户排班分配列表成功", assignments));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取用户排班分配列表失败: " + e.getMessage()));
        }
    }

    /**
     * 根据日期范围获取排班分配列表
     */
    @GetMapping("/dateRange")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<ScheduleAssignment>>> getScheduleAssignmentsByDateRange(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        try {
            List<ScheduleAssignment> assignments = scheduleAssignmentService.getScheduleAssignmentsByDateRange(startDate, endDate);
            return ResponseEntity.ok(ApiResponse.success("获取日期范围排班分配列表成功", assignments));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取日期范围排班分配列表失败: " + e.getMessage()));
        }
    }

    /**
     * 根据班次ID获取排班分配列表
     */
    @GetMapping("/shift/{shiftId}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<ScheduleAssignment>>> getScheduleAssignmentsByShiftId(@PathVariable String shiftId) {
        try {
            List<ScheduleAssignment> assignments = scheduleAssignmentService.getScheduleAssignmentsByShiftId(shiftId);
            return ResponseEntity.ok(ApiResponse.success("获取班次排班分配列表成功", assignments));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取班次排班分配列表失败: " + e.getMessage()));
        }
    }

    /**
     * 根据用户和日期获取排班分配
     */
    @GetMapping("/user/{userId}/date/{date}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<ScheduleAssignment>>> getScheduleAssignmentsByUserAndDate(
            @PathVariable Integer userId,
            @PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        try {
            List<ScheduleAssignment> assignments = scheduleAssignmentService.getScheduleAssignmentsByUserAndDate(userId, date);
            return ResponseEntity.ok(ApiResponse.success("获取用户日期排班分配成功", assignments));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取用户日期排班分配失败: " + e.getMessage()));
        }
    }

    /**
     * 更新排班分配
     */
    @PutMapping("/update")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> updateScheduleAssignment(@RequestBody ScheduleAssignment assignment) {
        try {
            boolean success = scheduleAssignmentService.updateScheduleAssignment(assignment);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("更新排班分配成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("更新排班分配失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新排班分配失败: " + e.getMessage()));
        }
    }

    /**
     * 删除排班分配
     */
    @DeleteMapping("/delete/{id}")
    @PreAuthorize("hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> deleteScheduleAssignment(@PathVariable String id) {
        try {
            boolean success = scheduleAssignmentService.deleteScheduleAssignment(id);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("删除排班分配成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("删除排班分配失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除排班分配失败: " + e.getMessage()));
        }
    }

    /**
     * 更新排班分配状态
     */
    @PutMapping("/status/{id}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Void>> updateScheduleAssignmentStatus(
            @PathVariable String id,
            @RequestParam String status) {
        try {
            boolean success = scheduleAssignmentService.updateScheduleAssignmentStatus(id, status);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("更新排班分配状态成功", null));
            } else {
                return ResponseEntity.ok(ApiResponse.error("更新排班分配状态失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新排班分配状态失败: " + e.getMessage()));
        }
    }

    /**
     * 分页查询排班分配列表
     */
    @GetMapping("/pagedList")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<PageResult<ScheduleAssignment>>> getPagedScheduleAssignmentList(
            @RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "shiftId", required = false) String shiftId,
            @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(value = "status", required = false) String status) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("current", current);
            params.put("pageSize", pageSize);
            params.put("offset", (current - 1) * pageSize);
            
            if (userId != null) {
                params.put("userId", userId);
            }
            if (shiftId != null && !shiftId.trim().isEmpty()) {
                params.put("shiftId", shiftId.trim());
            }
            if (startDate != null) {
                params.put("startDate", startDate);
            }
            if (endDate != null) {
                params.put("endDate", endDate);
            }
            if (status != null && !status.trim().isEmpty()) {
                params.put("status", status.trim());
            }
            
            PageResult<ScheduleAssignment> pageResult = scheduleAssignmentService.getPagedScheduleAssignmentList(params);
            return ResponseEntity.ok(ApiResponse.success("获取排班分配列表成功", pageResult));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取排班分配列表失败: " + e.getMessage()));
        }
    }

    /**
     * 智能排班生成
     */
    @PostMapping("/generate")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<List<ScheduleAssignment>>> generateSmartSchedule(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(required = false) List<Integer> userIds,
            @RequestParam(required = false) List<String> shiftIds) {
        try {
            // 设置创建人
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            // 这里需要根据username获取userId，暂时设置为1
            Integer createdBy = 1;
            
            List<ScheduleAssignment> assignments = scheduleAssignmentService.generateSmartSchedule(
                    startDate, endDate, createdBy);
            
            return ResponseEntity.ok(ApiResponse.success("智能排班生成成功", assignments));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("智能排班生成失败: " + e.getMessage()));
        }
    }

    /**
     * 统计用户排班次数
     */
    @GetMapping("/statistics/user/{userId}")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Integer>> getUserScheduleCount(
            @PathVariable Integer userId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        try {
            Integer count = scheduleAssignmentService.countUserAssignmentsInDateRange(userId, startDate, endDate);
            return ResponseEntity.ok(ApiResponse.success("获取用户排班次数成功", count));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取用户排班次数失败: " + e.getMessage()));
        }
    }

    /**
     * 检查排班冲突
     */
    @PostMapping("/check/conflict")
    @PreAuthorize("hasRole('COUNSELOR') or hasRole('MINISTER') or hasRole('SYSTEM_ADMIN') or hasRole('SUPER_ADMIN')")
    public ResponseEntity<ApiResponse<Boolean>> checkScheduleConflict(@RequestBody ScheduleAssignment assignment) {
        try {
            boolean hasConflict = scheduleAssignmentService.checkScheduleConflict(assignment);
            
            if (hasConflict) {
                return ResponseEntity.ok(ApiResponse.success("存在排班冲突", true));
            } else {
                return ResponseEntity.ok(ApiResponse.success("无排班冲突", false));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("检查排班冲突失败: " + e.getMessage()));
        }
    }
}